package com.wwk.controller;

import com.aliyuncs.exceptions.ClientException;
import com.wwk.constant.MessageConstant;
import com.wwk.constant.RedisConstant;
import com.wwk.entity.Result;
import com.wwk.utils.SMSUtils;
import com.wwk.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * @Classname ValidateCodeController
 * @Description TODO
 * @Date 2020/11/7 15:39
 * @Created by com.wwk
 * @Author com.wwk
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    //预约发送验证码
    @RequestMapping("/send4Order")
    public Result send4Order(String phone) {
        if(phone!=null&&phone.length()>0){
            //生成4位验证码
            final Integer code = ValidateCodeUtils.generateValidateCode(4);
            try{
                //传输验证码和手机号 //发送短信
                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,phone,String.valueOf(code));
            }catch (ClientException e){
                e.printStackTrace();
                //发送失败
                return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
            }
            System.out.println("发送的手机验证码为：" + code);
            //将生成的验证码缓存到redis
            //Redis Setex 命令为指定的 key 设置值及其过期时间。如果 key 已经存在， SETEX 命令将会替换旧的值
            jedisPool.getResource().setex( phone + RedisConstant.SENDTYPE_ORDER,5 * 60,code.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }
        return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
    }

    //登陆发送验证码
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone){
        //生成6位验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        try{
            //传输验证码和手机号 //发送短信
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,String.valueOf(code));
        }catch (ClientException e){
            e.printStackTrace();
            //发送失败
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        System.out.println("发送的手机验证码为：" + code);
        //将生成的验证码缓存到redis
        //Redis Setex 命令为指定的 key 设置值及其过期时间。如果 key 已经存在， SETEX 命令将会替换旧的值
        jedisPool.getResource().setex( telephone + RedisConstant.SENDTYPE_LOGIN,5 * 60,code.toString());
        return new Result(true, MessageConstant.SEND_VALIDATECODE_FAIL);
    }

}
